﻿//	Copyright (c) 2013 Jonathan Loe
//
//	MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights 
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
//	of the Software, and to permit persons to whom the Software is furnished to do so, 
//	subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in all 
//	copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
//	INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
//	PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
//	FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
//	ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

using Ordinaire;
using Ordinaire.Data;

namespace Ordinaire.Commerce.Data
{
    /// <summary>
    /// Represents table 'Goods' in the underlying database.
    /// </summary>
    [Table]
    public class Goods : Data<int, string>
    {
        #region Variables

        /// <summary>
        /// Storage for association "FK_Goods_MeasureUnits".
        /// </summary>
        private EntityRef<MeasureUnits> measureUnits;

        /// <summary>
        /// Storage for one-to-many relationship to 'CompositeGoods' table.
        /// </summary>
        private EntitySet<CompositeGoods> compositeGoods = new EntitySet<CompositeGoods>();

        #endregion

        #region Property methods

        /// <summary>
        /// Gets or sets the entry unique identifier.
        /// </summary>
        [Column(IsPrimaryKey = true, IsDbGenerated = true, UpdateCheck = UpdateCheck.Never)]
        public override int Id
        {
            get { return base.Id; }
            set { base.Id = value; }
        }

        /// <summary>
        /// Gets or sets the code or barcode assigned for the good.
        /// </summary>
        [Column(DbType = "nvarchar(50) NULL", UpdateCheck = UpdateCheck.Never)]
        public string Code { get; set; }

        /// <summary>
        /// Gets or sets the good name.
        /// </summary>
        [Column(DbType = "nvarchar(250) NOT NULL", UpdateCheck = UpdateCheck.Never)]
        public override string Name
        {
            get { return base.Name; }
            set { base.Name = value; }
        }

        /// <summary>
        /// Gets or sets the measureable unit.
        /// </summary>
        [Column(DbType = "int NULL", CanBeNull = true, UpdateCheck = UpdateCheck.Never)]
        public int? MeasureUnitId { get; set; }

        /// <summary>
        /// Gets or set the value/price of a good.
        /// </summary>
        [Column(DbType = "money NOT NULL DEFAULT(0)", UpdateCheck = UpdateCheck.Never)]
        public decimal Value { get; set; }

        /// <summary>
        /// Get or set the username who created this entry.
        /// </summary>
        [Column(DbType = "nvarchar(10) NOT NULL", UpdateCheck = UpdateCheck.Never)]
        public override string CreatedBy
        {
            get { return base.CreatedBy; }
            set { base.CreatedBy = value; }
        }

        /// <summary>
        /// Get or set the date when the entry was first created.
        /// </summary>
        [Column(DbType = "datetime", UpdateCheck = UpdateCheck.Never)]
        public override DateTime? CreateDate
        {
            get { return base.CreateDate; }
            set { base.CreateDate = value; }
        }

        /// <summary>
        /// Get or set the username who last updated this entry.
        /// </summary>
        [Column(DbType = "nvarchar(10)", UpdateCheck = UpdateCheck.Never)]
        public override string UpdatedBy
        {
            get { return base.UpdatedBy; }
            set { base.UpdatedBy = value; }
        }

        /// <summary>
        /// Get or set the date when the entry was last updated.
        /// </summary>
        [Column(DbType = "datetime")]
        public override DateTime? UpdateDate
        {
            get { return base.UpdateDate; }
            set { base.UpdateDate = value; }
        }

        #endregion

        #region Association

        /// <summary>
        /// Gets or sets the associated data from table 'MeasureUnit'.
        /// </summary>
        [Association(Name = "FK_Goods_MeasureUnits", IsForeignKey = true, ThisKey = "MeasureUnitId", Storage = "measureUnits")]
        public MeasureUnits MeasureUnits
        {
            get { return this.measureUnits.Entity; }
            set { this.measureUnits.Entity = value; }
        }

        /// <summary>
        /// Gets or sets the associated data to table 'CompositeGoods'.
        /// </summary>
        [Association(ThisKey = "Id", OtherKey = "ParentId", Storage = "compositeGoods")]
        public EntitySet<CompositeGoods> CompositeGoods
        {
            get { return this.compositeGoods; }
            set { this.compositeGoods.Assign(value); }
        }

        #endregion

        #region Expression methods

        /// <summary>
        /// Returns an expression where good code/barcode is as specified.
        /// </summary>
        /// <param name="code">the code or barcode</param>
        /// <returns>the related expression</returns>
        public static Expression<Func<Goods, bool>> CodeIs(string code)
        {
            return d => d.Code.Equals(code);
        }

        #endregion
    }

    /// <summary>
    /// Contains list of extension methods for Ordinaire.Commerce.Data.Goods.
    /// </summary>
    public static class GoodsExtension
    {
        /// <summary>
        /// Converts to an entity representation/instance of a data in table 'Goods'.
        /// </summary>
        /// <param name="data">the data to convert</param>
        /// <returns>the entity instance</returns>
        public static Good ToGood(this Goods data)
        {
            return data.ToGood<Good>();
        }

        /// <summary>
        /// Converts to an entity representation/instance of a data in table 'Goods'.
        /// </summary>
        /// <typeparam name="TGood">derived type of Ordinaire.Commerce.Good</typeparam>
        /// <param name="data">the data to convert</param>
        /// <returns>the entity instance of the specified type</returns>
        public static TGood ToGood<TGood>(this Goods data)
            where TGood : Good
        {
            if (data == null)
            {
                return default(TGood);
            }

            TGood instance = typeof(TGood).Instance<TGood>();
            instance.Id    = data.Id;
            instance.Code  = data.Code;
            instance.Name  = data.Name;
            instance.Value = data.Value;
            
            if (data.CompositeGoods.HasLoadedOrAssignedValues)
            {
                List<CompositeGoods> composites = data.CompositeGoods.ToList();

                instance.IsComposite = composites.Count() > 0;
                if (instance.IsComposite)
                {
                    instance.Compositions = new List<GoodComposition>();

                    CompositeGoods record = null;
                    int compositesCount = composites.Count;
                    for (int i = 0; i < compositesCount; i++)
                    {
                        record = composites[i];
                        instance.Compositions.Add(record.ToGoodComposition());
                    }
                }
            }

            if (data.MeasureUnits != null)
            {
                instance.Unit = data.MeasureUnits.Name;
            }

            return instance;
        }
    }
}
